var datatable;// 定义一个全局的dataTable
var d;
var exportColumns;// 导出的列
var params;// 查询参数
$(function() {
	isGoing();
	//新加
	 var sp = $("#sp").val();
	 loadSite(sp);
	 $("#sp").combobox({
		select : function(event, ui) {
			loadSite();
		},
		width : 100
	 });
	 
	
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});

	
	$("#channelId").combobox();
	$("#area").combobox();
	showArearList("area");
	
	$("#groupId").combobox();
	$("#terminalBrandId").combobox({
		select : function(event, ui) {
			loadTerminalModel();
		}
	});
	$("#terminalModelId").combobox();
	$("#sgw").combobox();
})

function isGoing(){
	var callId = $("#callId").val();
	if(callId){
		var terminalBrandId = $("#terminalBrandId").val();
		if(terminalBrandId){
			loadTerminalModel();
		}
		getList();
	}
}

/**
 * 新加 
 * 
 * 
 */

function loadSite(sp) {
	var sp = $("#sp").val();
	$.ajax({
				url : '../../feature/sp/getSiteInfos?sp='
					+ sp,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#site").remove();
					$("#site").empty();
					$("#siteTD")
							.append(
									$("<select id='site' name='site'></select>"));
					$("#site").combobox();
					$("#site").append("<option value=''>全部</option>");
					var list = msg.siteList;
					$.each(eval(list), function(i, item) {
						$(
								"<option value='" + item.site + "'>"
										+ item.site + "</option>")
								.appendTo($("#site"));
					});
				}
			});
}

/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */
function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();

	$
			.ajax({
				url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
						+ terminalBrand,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#terminalModelId").remove();
					
					$("#terminalModelTD")
							.append(
									$("<select id='terminalModelId' name='terminalModelId'></select>"));
					$("#terminalModelId").append("<option value=''>全部</option>");
					$("#terminalModelId").combobox();
					var list = msg.terminalModelList;
					var terminalModelSelected =  $("#terminalModelSelected").val();
					if(terminalModelSelected){
						$.each(eval(list), function(i, item) {
							if(terminalModelSelected==item.terminal_model){
								$(
										"<option selected='selected' value='" + item.terminal_model + "'>"
										+ item.terminal_model + "</option>")
										.appendTo($("#terminalModelId"));
							}else{
								$(
										"<option value='" + item.terminal_model + "'>"
										+ item.terminal_model + "</option>")
										.appendTo($("#terminalModelId"));
							}
						});

					}else{
						
						$.each(eval(list), function(i, item) {
							$(
									"<option value='" + item.terminal_model + "'>"
									+ item.terminal_model + "</option>")
									.appendTo($("#terminalModelId"));
						});
					}
				}
			});

}
/**
 * 获得单选框
 */
function getRadio() {
	var selectedvalue = $("input[name='radio']:checked").val();
	for (var i = 0; i < 5; i++) {
		var tempId = '#radio_' + i;
		if (selectedvalue == i) {
			$(tempId).show();
		} else {
			$(tempId).hide();
		}
	}
}
/**
 * 页面校验
 */
function validatorParam() {
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	if (beginDate == null || beginDate == '') {
		alert("请选择开始时间");
		return false;
	}
	if (endDate == null || endDate == '') {
		alert("请选择结束时间");
		return false;
	}
	return true;
}
function getList() {
	delete d;
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	//类型
	var typeRadio = $('input:radio[name="typeRadio"]:checked').val();
	
	//新加的 
	var sp = $("#sp").val();
	var site = $("#site").val();
	
	var webSite = $("#webSiteId").val();
	var channelId = $("#channelId").val();
	var channelName=$("#channelId").find("option:selected").text()
	//时间
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	// 维度
	var selectRadio = $('input:radio[name="radio"]:checked').val();
	
	var groupId = $("#groupId").val();
	var userId = $("#userId").val();

	var terminalBrandId = $("#terminalBrandId").val();
	var terminalModelId = $("#terminalModelId").val();
	var sgw = $("#sgw").val();
	var cityCode = $("#area").val();
	var eNodeBID = $("#eNodeBID").val();
	var areaHouse = $("#areaHouse").val();

	if (validatorParam()) {
		//$("#table tbody tr").remove();
		$("#tbodyId").remove();
		$('#table').append($("<tbody id='tbodyId'></tbody>"));
		if (datatable == undefined || datatable == "undefined"
				|| datatable == null) {
		} else {
			datatable.fnDestroy();
		}
		// 构造页面显示列
		var columns = createColumns(typeRadio, selectRadio);
		

		datatable = $('#table')
				.dataTable(
						{
							"aoColumnDefs" : [ {
						        sDefaultContent : '',
						        aTargets : [ '_all' ]
						    } ],
							"bPaginate" : true, // 翻页功能
							"bLengthChange" : false, // 改变每页显示数据数量
							"bFilter" : false, // 过滤功能
							"bSort" : true, // 排序功能
							"bInfo" : true,// 页脚信息
							"bAutoWidth" : true,// 自动宽度
							// "sPaginationType": "full_numbers",//显示分页的样式
							// 还有simple_numbers等
//							"sScrollX" : "100%",
							"sScrollXInner" : "110%",
							"iDisplayLength" : 50,
							"bScrollCollapse" : true,
							"oLanguage" : {
								"sLengthMenu" : "每页显示 _MENU_条",
								"sZeroRecords" : "没有找到符合条件的数据",
								"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
								"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
								"sInfoEmpty" : "没有记录",
								"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
								"sSearch" : "搜索：",
								"oPaginate" : {
									"sFirst" : "首页",
									"sPrevious" : "前一页",
									"sNext" : "后一页",
									"sLast" : "尾页"
								}
							},
							"bProcessing" : true,
							"bServerSide" : true,
							"sAjaxSource" : "../../businessAnalysis/sp/infos",
							"fnServerData" : function(sSource, aoData,
									fnCallback) {
								// 清空一次参数，保证每次查询都是最新的
								delete params;
								
								var areaBoxStr="";
								$("input[name='areaBox']:checkbox").each(function() {
									if ($(this).attr("checked")) {
										areaBoxStr +=$(this).val()+"|";
									}
								});
								
								params = {
										"aoData" : JSON.stringify(aoData),
										"typeRadio":typeRadio,
										"sp":sp,
										"site":site,
										"webSite":webSite,
										"channelId":channelId,
										"channelName":channelName,
										"timeSize" : timeSize,
										"beginDate" : beginDate,
										"endDate" : endDate,
										"selectRadio" : selectRadio,
										"groupId" : groupId,
										"userId" : userId,
										"terminalBrandId" : terminalBrandId,
										"terminalModelId" : terminalModelId,
										"sgw" : sgw,
										"cityCode" : cityCode,
										"eNodeBID" : eNodeBID,
										"areaHouse" : areaHouse,
										"areaBoxStr":areaBoxStr
								};
								$.ajax({
											"type" : "POST",
											"contentType" : "application/x-www-form-urlencoded",
											"url" : sSource,
											"dataType" : "json",
											"data" : params, // 以json格式传递
											"success" : function(resp) {
												fnCallback(resp.pageDate);
												d = resp.allData;
											}
										});
							},
							columns : columns

						});
	   }
}

/**
 * 构造页面显示的列
 * 
 * @param businessAppBox
 * @param selectRadio
 */
function createColumns(typeRadio, selectRadio) {
	
	var columns = [];
	exportColumns = [];
	var trObj = $('#trId');
	trObj.children().remove();
	// 时间
	trObj.append($("<th>时间</th>"));
	columns.push({
		data : "report_date"
	});
	exportColumns.push({
		"key" : "report_date",
		"name" : "时间",
		"value" : ""
	});
	
	// 根据页面条件显示
	if (typeRadio == '0') {
		trObj.append($("<th >网站</th>"));
		columns.push({
			data : "web_site",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		exportColumns.push({
			"key" : "web_site",
			"name" : "网站",
			"value" : ""
		});
	}else if(typeRadio == '1'){
		trObj.append($("<th >频道</th>"));
		columns.push({
			data : "channel_name"
		});
		exportColumns.push({
			"key" : "channel_name",
			"name" : "频道",
			"value" : ""
		});
	}else if(typeRadio == '2'){  //SP
		trObj.append($("<th >SP</th>"));
		columns.push({
			data : "sp"
		});
		exportColumns.push({
			"key" : "sp",
			"name" : "sp",
			"value" : ""
		});
		
		if ($('#site').val() != '') {// 网站
			trObj.append($("<th >网站</th>"));
			columns.push({
				data : "web_site"
			});
			exportColumns.push({
				"key" : "web_site",
				"name" : "web_site",
				"value" : ""
			});
		}
	}
	// SWG
	if (selectRadio == '3') {
		trObj.append($("<th >SGW</th>"));
		columns.push({
			data : "sgw_name",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		exportColumns.push({
			"key" : "sgw_name",
			"name" : "SGW",
			"value" : ""
		});
	} else if (selectRadio == '4') {// 区域
		// 城市
		trObj.append($("<th >地市</th>"));
		columns.push({
			data : "city_name"
		});
		exportColumns.push({
			"key" : "city_code",
			"name" : "地市",
			"value" : ""
		});
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox").each(function() {
			if ($(this).attr("checked")) {
				var areatBoxId = $(this).val();
				if (areatBoxId == '1') {// eNodeBID
					trObj.append($("<th >eNodeBID</th>"));
					columns.push({
						data : "enodeb_name"
					});
					exportColumns.push({
						"key" : "enodeb_name",
						"name" : "eNodeBID",
						"value" : ""
					});
				} else if (areatBoxId == '2') {// 小区
					trObj.append($("<th >小区</th>"));
					columns.push({
						data : "cell_name"
					});
					exportColumns.push({
						"key" : "cell_name",
						"name" : "小区",
						"value" : ""
					});
				}
			}
		});
		if( $("input[name='areaBox']:checkbox").is(':checked') ==false){
			// 用户数
			trObj.append($("<th>用户数</th>"));
			columns.push({
				data : "user_num"
			});
			exportColumns.push({
				"key" : "user_total",
				"name" : "用户数",
				"value" : ""
			});
		}
	} else if (selectRadio == '0') {// 用户组
		trObj.append($("<th >用户组</th>"));
		columns.push({
			data : "group_name",
			render : function(value, type, row) {
//				$("#groupId option").each(function() {
//					if ($(this).val() == value) {
//						groupName = $(this).text();
//					}
//				});
				if(value==null ){
					value = "";
				}
				return value;
			}
		
		});
		//后台需要处理
		exportColumns.push({
			"key" : "group_name",
			"name" : "用户组",
			"value" :""
		});
	} else if (selectRadio == '1') {// 用户
		trObj.append($("<th >MSISDN</th>"));
		columns.push({
			data : "msisdn"
		});
		exportColumns.push({
			"key" : "msisdn",
			"name" : "MSISDN",
			"value" : ""
		});
//		trObj.append($("<th >IMSI</th>"));
//		columns.push({
//			data : "imsi"
//		});
//		exportColumns.push({
//			"key" : "imsi",
//			"name" : "IMSI",
//			"value" : ""
//		});
	} else if (selectRadio == '2') {// 终端
		trObj.append($("<th >终端类型</th>"));
		columns.push({
			data : "terminal_brand",
			render : function(value,type,row){
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		
		exportColumns.push({
			"key":"terminal_brand",
			"name":"终端类型",
			"value":""
		});
		
		var terminalModelName="";
		trObj.append($("<th >终端型号</th>"));
		columns.push({
			data : "terminal_model",
			render : function(value,type,row){
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
//				,
//			render : function(value, type, row) {
//				$("#terminalModelId option").each(function() {
//					if ($(this).val() == value) {
//						terminalModelName = $(this).text();
//					}
//				});
//				return terminalModelName;
//			}
		});
		exportColumns.push({
			"key":"terminal_model",
			"name":"终端型号",
			"value":""
		});
	}
	// 总流量
	trObj.append($("<th>总流量(M)</th>"));
	columns.push({
		data : "flow_total",
		render : function(value, type, row) {
			var paramDate = row.report_date;
			return "<a href='#' style=\"text-decoration: underline;\" onclick=\"forwordCommonPerformance('"
					+ paramDate
					+ "')\"  >" + value + "</a>";
		}
	});
	exportColumns.push({
		"key" : "flow_total",
		"name" : "总流量(M)",
		"value" : ""
	});
	// 上行包数
	trObj.append($("<th>上行包数</th>"));
	columns.push({
		data : "packet_total_up"
	});
	exportColumns.push({
		"key" : "packet_total_up",
		"name" : "上行包数",
		"value" : ""
	});
	// 下行包数
	trObj.append($("<th>下行包数</th>"));
	columns.push({
		data : "packet_total_down"
	});
	exportColumns.push({
		"key" : "packet_total_down",
		"name" : "下行包数",
		"value" : ""
	});
	// 上行流量
	trObj.append($("<th>上行流量(M)</th>"));
	columns.push({
		data : "flow_up"
	});
	exportColumns.push({
		"key" : "flow_up",
		"name" : "上行流量(M)",
		"value" : ""
	});
	// 下行流量
	trObj.append($("<th>下行流量(M)</th>"));
	columns.push({
		data : "flow_down"
	});
	exportColumns.push({
		"key" : "flow_down",
		"name" : "下行流量(M)",
		"value" : ""
	});
	// 下载速率
	trObj.append($("<th>下载速率(M/S)</th>"));
	columns.push({
		data : "download_speed"
	});
	exportColumns.push({
		"key" : "download_speed",
		"name" : "下载速率(M/S)",
		"value" : ""
	});
	// 首包时延
	trObj.append($("<th>首包时延</th>"));
	columns.push({
		data : "firstpacket_delay"
	});
	exportColumns.push({
		"key" : "firstpacket_delay",
		"name" : "首包时延",
		"value" : ""
	});
	// 首页时延
	trObj.append($("<th>首页时延</th>"));
	columns.push({
		data : "first_page_delay",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = "-";
			}
			return value;
		}
	});
	exportColumns.push({
		"key" : "first_page_delay",
		"name" : "首页时延",
		"value" : ""
	});

	return columns;
}

function resetQueryForm() {
	$('#queryForm')[0].reset();
	getRadio();
}

function exportExcel() {
	if (d) {
		params['exportColumns'] = JSON.stringify(exportColumns);
		$
				.ajax({
					type : "POST",
					url : "../../businessAnalysis/sp/exportBigDataExcel?rand="
							+ Math.random(),
					dataType : "json",
					"data" : params,
					success : function(data) {
						if (data.flag) {
							var url = "../../businessAnalysis/attachment/downFiles?path="
									+ data.path;
							window.location.href = url;
						} else {
							alert(data.msgs);
						}
					}
				});
	} else {
		alert("请先查询数据！");
	}
}

/**
 * 跳转到通用性能分析页面
 */
function forwordCommonPerformance(paramDate){
	var areaBoxStr="";
	$("input[name='areaBox']:checkbox").each(function() {
		if ($(this).attr("checked")) {
			areaBoxStr +=$(this).val()+"|";
		}
	});
	
	//var citySel = $("#citySel").val();
	var url = "/businessAnalysis/commonBusinessPerformance/index?params=" + escape($("#queryForm").serialize())
		+ "&paramDate=" + paramDate +"&areaBoxStr="+areaBoxStr;
		linkTab("通用业务性能", url);
}

/*// 下拉树 begin
function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree
			.getSelectedNodes(), v = "";
	nodes.sort(function compare(a, b) {
		return a.id - b.id;
	});
	for (var i = 0, l = nodes.length; i < l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0)
		v = v.substring(0, v.length - 1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);

	hideMenu();
}*/
/**
 * 显示树
 *//*
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({
		left : cityOffset.left - 26 + "px",
		top : cityOffset.top - 206 + "px"
	}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
*//**
 * 隐藏树
 *//*
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
			event.target).parents("#menuContent").length > 0)) {
		hideMenu();
	}
}*/